<!-- 应急救援首页面 -->
<template>
	<view>
		<uni-notice-bar color="#EA1703" background-color="#FFFFFF" style="width:650rpx; height:10rpx;" show-icon
			scrollable text="目前救援服务暂不支持高架和高速救援，请等待上架" />
		<view class="page-body" style="height: 400rpx;">
			<view class="page-section page-section-gap">
				<map style="width: 100%; height: 200px;" :latitude="latitude" :longitude="longitude" :markers="covers">
				</map>
			</view>
		</view>
		<uni-forms label-width="170rpx" ref="baseFormData" :model="baseFormData" class="basic" @submit="submit">
			<view class="uni-padding-wrap">
				<uni-segmented-control :current="current" :values="items" style-type="text" active-color="#dd524d"
					@clickItem="onClickItem" />
			</view>
			<view class="content">
				<view v-if="current === 0">
					<uni-forms-item label="起点" :required="false" location="position" class="inputs" name="position">
						<uni-easyinput :inputBorder="false" v-model="baseFormData.position" inputBorder
							style="width: 400rpx;margin-right: 100rpx;" placeholder="河南省焦作区山阳市32号" />
					</uni-forms-item>
					<uni-forms-item label="终点" :required="false" location="position" class="inputs" name="position">
						<uni-easyinput :inputBorder="false" v-model="baseFormData.end" inputBorder
							style="width: 400rpx;margin-right: 100rpx;" placeholder="河南省焦作区山阳市32号" />
					</uni-forms-item>
					<uni-forms-item label="救助人" :required="false" Rescuers="name" class="inputs" name="name">
						<uni-easyinput :inputBorder="false" v-model="baseFormData.name" inputBorder
							style="width: 400rpx;margin-right: 100rpx;" placeholder="杨子" />
					</uni-forms-item>
					<uni-forms-item label="联系方式" :required="false" phone="phone" class="inputs" name="phone">
						<uni-easyinput :inputBorder="false" v-model="baseFormData.phone" inputBorder
							style="width: 400rpx;margin-right: 100rpx;" placeholder="175305779658" />
					</uni-forms-item>
					<uni-forms-item label="车牌" :required="false" plate="carNum" class="inputs" name="carNum">
						<uni-easyinput :inputBorder="false" v-model="baseFormData.carNum" inputBorder
							style="width: 400rpx;margin-right: 100rpx;" placeholder="豫CJ5652" />
					</uni-forms-item>
					<uni-easyinput type="textarea" autoHeight v-model="baseFormData.description" />
					<text>请准确描述当前状况与所需帮助</text>

				</view>
				<view v-if="current === 1">
					<uni-forms-item label="起点" :required="false" location="position" class="inputs" name="position">
						<uni-easyinput :inputBorder="false" v-model="baseFormData.position" inputBorder
							style="width: 400rpx;margin-right: 100rpx;" placeholder="河南省焦作区山阳市32号" />
					</uni-forms-item>
					<uni-forms-item label="终点" :required="false" location="position" class="inputs" name="position">
						<uni-easyinput :inputBorder="false" v-model="baseFormData.end" inputBorder
							style="width: 400rpx;margin-right: 100rpx;" placeholder="河南省焦作区山阳市32号" />
					</uni-forms-item>
					<uni-forms-item label="救助人" :required="false" Rescuers="name" class="inputs" name="name">
						<uni-easyinput :inputBorder="false" v-model="baseFormData.name" inputBorder
							style="width: 400rpx;margin-right: 100rpx;" placeholder="杨子" />
					</uni-forms-item>
					<uni-forms-item label="联系方式" :required="false" phone="phone" class="inputs" name="phone">
						<uni-easyinput :inputBorder="false" v-model="baseFormData.phone" inputBorder
							style="width: 400rpx;margin-right: 100rpx;" placeholder="175305779658" />
					</uni-forms-item>
					<uni-forms-item label="车牌" :required="false" plate="carNum" class="inputs" name="carNum">
						<uni-easyinput :inputBorder="false" v-model="baseFormData.carNum" inputBorder
							style="width: 400rpx;margin-right: 100rpx;" placeholder="豫CJ5652" />
					</uni-forms-item>
					<uni-easyinput type="textarea" autoHeight v-model="baseFormData.description" />
					<text>请准确描述当前状况与所需帮助</text>
				</view>
				<view v-if="current === 2" style="margin-top: 115rpx;">
					<uni-forms-item label="起点" :required="false" location="position" class="inputs" name="position">
						<uni-easyinput :inputBorder="false" v-model="baseFormData.position" inputBorder
							style="width: 400rpx;margin-right: 100rpx;" placeholder="河南省焦作区山阳市32号" />
					</uni-forms-item>
					<uni-forms-item label="终点" :required="false" location="end" class="inputs" name="end">
						<uni-easyinput :inputBorder="false" v-model="baseFormData.end" inputBorder
							style="width: 400rpx;margin-right: 100rpx;" placeholder="河南省焦作区山阳市32号" />
					</uni-forms-item>
					<uni-forms-item label="救助人" :required="false" Rescuers="name" class="inputs" name="name">
						<uni-easyinput :inputBorder="false" v-model="baseFormData.name" inputBorder
							style="width: 400rpx;margin-right: 100rpx;" placeholder="杨子" />
					</uni-forms-item>
					<uni-forms-item label="联系方式" :required="false" phone="phone" class="inputs" name="phone">
						<uni-easyinput :inputBorder="false" v-model="baseFormData.phone" inputBorder
							style="width: 400rpx;margin-right: 100rpx;" placeholder="175305779658" />
					</uni-forms-item>
					<uni-forms-item label="车牌" :required="false" plate="carNum" class="inputs" name="carNum">
						<uni-easyinput :inputBorder="false" v-model="baseFormData.carNum" inputBorder
							style="width: 400rpx;margin-right: 100rpx;" placeholder="豫CJ5652" />
					</uni-forms-item>
					<uni-forms-item label="车型" :required="false" plate="carType" class="inputs" name="carType">
						<uni-data-select v-model="baseFormData.carType" :localdata="range" @change="change"
							style="width:400rpx;">
							<!-- <el-option v-for="item in range" :key="item.id" :label="item.name" :value="item.id" /> -->
						</uni-data-select>
					</uni-forms-item>
					<uni-easyinput type="textarea" autoHeight v-model="baseFormData.description" />
					<text>请准确描述当前状况与所需帮助</text>
				</view>
			</view>

			<view class="mintitle">
				警务求助
			</view>
			<view class="block">
				<view class="helptitle">
					交通事故
					<view class="helpphone">
						122
					</view>
				</view>
				<view class="helptitle">
					急救中心
					<view class="helpphone">
						120
					</view>
				</view>
				<view class="helptitle">
					火警
					<view class="helpphone">
						119
					</view>
				</view>
				<view class="helptitle">
					公安报警
					<view class="helpphone">
						110
					</view>
				</view>
			</view>
			<button class="btn" type="primary" @click="submit('baseFormData')"
				style="width: 480rpx;border-radius: 50rpx; margin-left: 130rpx;margin-top: 50rpx;height: 80rpx;font-size: 30rpx;font-weight: 550;background-color: #FD9518;">
				呼叫救援</button>
			<navigator class="records" url="/pages/earlyWarning/RescueRecords/RescueRecords">
				救援记录>
			</navigator>
		</uni-forms>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				is_open_socket: false,
				socketTask: null,
				baseFormData: {
					position: "", //位置
					end: "", //终点
					name: "", //救助人
					phone: "", //联系方式
					carNum: "", //车牌
					starting: "", //起点
					terminal: "", //终点
					carType: "", //车型
					current: "", //类型
					description: '', //描述
				},

				newbaseFormData: {
					position: "", //位置
					end: "", //终点
					name: "", //救助人
					phone: "", //联系方式
					carNum: "", //车牌
					starting: "", //起点
					terminal: "", //终点
					carType: "", //车型
					current: "" //类型
				},
				items: [],
				current: 0,
				carType: 0,
				range: [],
				id: 0, // 使用 marker点击事件 需要填写id
				title: 'map',
				latitude: 39.909,
				longitude: 116.39742,
				covers: [{
					latitude: 39.909,
					longitude: 116.39742,
					iconPath: '../../../static/location.png',
					title: "兔师傅"
				}, {
					latitude: 39.90,
					longitude: 116.39,
					iconPath: '../../../static/location.png',
					title: "小李补胎"
				}]
			}
		},
		onLoad(options) {
			this.connectSocketInit();
		},
		methods: {
			onClickItem(e) {
				if (this.current !== e.currentIndex) {
					this.current = e.currentIndex
				}
				if (this.current == 0) {
					this.baseFormData.starting = "";
					this.baseFormData.terminal = "";
					this.baseFormData.carType = "";
				} else if (this.current == 1) {
					this.baseFormData.starting = "";
					this.baseFormData.terminal = "";
					this.baseFormData.carType = "";
				} else if (this.current == 2) {
					this.baseFormData.position = "";
					this.baseFormData.carNum = "";
				}
				console.log(this.current)
			},
			connectSocketInit() {
				// 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
				this.socketTask = uni.connectSocket({
					// 【非常重要】必须确保你的服务器是成功的,如果是手机测试千万别使用ws://127.0.0.1:9099【特别容易犯的错误】
					url: "ws://localhost:8888/server/{userId}/{clientType}",
					success(data) {
						console.log("websocket连接成功");
					},
				});

				// 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
				this.socketTask.onOpen((res) => {
					console.log("WebSocket连接正常打开中...！");
					this.is_open_socket = true;
					// 注：只有连接正常打开中 ，才能正常成功发送消息
					this.socketTask.send({
						data: "uni-app发送一条消息",
						success: () => {
							console.log("消息发送成功");
						},
					});
					// 注：只有连接正常打开中 ，才能正常收到消息
					this.socketTask.onMessage((res) => {
						console.log("收到服务器内容：" + res.data);
					});
				});

				// 这里仅是事件监听【如果socket关闭了会执行】
				this.socketTask.onClose(() => {
					console.log("WebSocket已经被关闭了");
					this.is_open_socket = false;
				});

				// 错误处理
				this.socketTask.onError((err) => {
					console.error("WebSocket连接发生错误:", err);
				});
			},

			// 关闭websocket【离开这个页面的时候执行关闭】
			closeSocket() {
				if (this.socketTask) {
					this.socketTask.close({
						success: (res) => {
							this.is_open_socket = false;
							console.log("关闭成功", res);
						},
						fail: (err) => {
							console.log("关闭失败", err);
						}
					});
				}
			},

			clickRequest() {
				if (this.is_open_socket) {
					// websocket的服务器的原理是:发送一次消息,同时返回一组数据【否则服务器会进去死循环崩溃】
					this.socketTask.send({
						data: "请求一次发送一次message",
						success: () => {
							console.log("消息发送成功");
						},
					});
				} else {
					console.log("WebSocket未连接，无法发送消息");
				}
			},
			submit(ref) {
				this.$refs[ref].validate().then(res => {
					// 获取用户信息  
					const userInfo = uni.getStorageSync('userInfo'); // 从本地存储获取用户信息  

					// 检查用户信息是否存在  
					if (userInfo) {
						const userId = userInfo.id; // 获取用户 ID  

						// 发送请求  
						uni.request({
							url: 'http://localhost:8080/merchant/rescueTask',
							method: 'POST',
							header: {
								'Authorization': 'Bearer ' + wx.getStorageSync('token')
							},
							data: {
								uid: userId, // 使用获取到的用户 ID  
								position: this.baseFormData.position,
								end: this.baseFormData.end, // 终点  
								name: this.baseFormData.name,
								phone: this.baseFormData.phone,
								carNum: this.baseFormData.carNum,
								starting: this.baseFormData.starting,
								terminal: this.baseFormData.terminal,
								carType: this.baseFormData.carType,
								typeId: this.current,
								description: this.baseFormData.description,
							},
							success: (res) => {
								console.log('请求成功:', res.data);
								if (res.statusCode == 200) {
									uni.showToast({
										title: "发送成功，等待救援",
										icon: 'none'
									});;

									// 通过WebSocket发送消息
									if (this.is_open_socket) {
										this.socketTask.send({
											data: JSON.stringify({
												action: 'rescueTaskSubmitted',
												data: {
													uid: userId,
													position: this.baseFormData
														.position,
													end: this.baseFormData.end,
													name: this.baseFormData.name,
													phone: this.baseFormData.phone,
													carNum: this.baseFormData.carNum,
													starting: this.baseFormData
														.starting,
													terminal: this.baseFormData
														.terminal,
													carType: this.baseFormData.carType,
													typeId: this.current,
													description: this.baseFormData
														.description,
												}
											}),
											success: () => {
												console.log("WebSocket消息发送成功");
												// // 消息发送成功后关闭 WebSocket 连接
												// this.closeSocket();
											},
											fail: (err) => {
												console.error("WebSocket消息发送失败:", err);
											}
										});
									} else {
										console.log("WebSocket未连接，无法发送消息");
									}
								}
							},
							fail: (err) => {
								console.error('请求失败:', err);
							}
						});
					} else {
						console.error('用户信息未找到，请确保用户已登录。');
					}
					console.log('success', res);
					uni.showToast({
						title: `校验通过`
					})
					setTimeout(function() {
						uni.navigateTo({
							url: "/pages/earlyWarning/RescueRecords/RescueRecords"
						})
					}, 1000)
				}).catch(err => {
					console.log('err', err);
				})
			},
			getTypeList() {
				uni.request({
					url: 'http://localhost:8080/merchant/rescueType/list',
					method: 'GET',
					header: {
						'Authorization': 'Bearer ' + wx.getStorageSync('token')
					},
					success: (resp) => {
						console.log(resp)
						if (resp && resp.data && Array.isArray(resp.data.rows)) {
							this.items = resp.data.rows;
							// 遍历 rows 数组，获取每个对象的 name 值  
							const names = this.items.map(item => item.name);
							this.items = names;
							// 打印所有 name 值  
							console.log('查询的名称:', names);
						} else {
							console.error('数据结构不正确', resp);
						}
					}
				})
			},
			getCarTypeList() {
				uni.request({
					url: 'http://localhost:8080/user/type/list',
					method: 'GET',
					header: {
						'Authorization': 'Bearer ' + wx.getStorageSync('token')
					},
					success: (resp) => {
						console.log(resp)
						if (resp && resp.data && Array.isArray(resp.data.rows)) {
							this.range = resp.data.rows;
							// 遍历 rows 数组，获取每个对象的 name 值  
							const names = this.range.map(item => ({
								value: item.id,
								text: item.name
							}));
							this.range = names;
							// 打印所有 name 值  
							console.log('查询的名称:', names);
						} else {
							console.error('数据结构不正确', resp);
						}
					}
				})
			},
			change(value) {
				console.log("Selected car type:", value);
				// 处理选择变化后的逻辑  
			}
		},
		mounted() {
			this.getTypeList(),
				this.getCarTypeList()
		},
		created() {
			//this.connectSocketInit();
		},
		beforeDestroy() {
			//this.closeSocket();
		}
	}
</script>


<style lang="scss">
	page {
		height: 100%;
		background-color: #fff;
	}

	.basic {
		background-color: white;
		height: 1100rpx;
	}

	.example-body {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		padding: 0;
	}


	.uni-padding-wrap {
		// width: 750rpx;
		padding: 0px 80px;
		height: 0;
		font-weight: 700;
	}

	.content {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
		align-items: center;
		height: 440px;
		margin-top: 30rpx;
		margin-left: 50rpx;
	}

	.content-text {
		font-size: 14px;
		color: #666;
	}

	.inputs {
		border-bottom: 1rpx #f3f3f3 solid;
		margin: 0 0;
		padding: 20rpx 0;
	}

	text {
		margin-left: 40rpx;
		color: #ff5558;
		font-weight: 600;
	}

	.mintitle {
		margin-top: 100rpx;
		margin-left: 60rpx;
		font-size: 30rpx;
		font-weight: 700;
	}

	.block {
		display: flex;
		flex-wrap: wrap;

	}

	.helptitle {
		font-size: 24rpx;
		margin-left: 60rpx;
		width: 300rpx;
		display: flex;
		justify-content: space-between;
	}

	.helpphone {
		color: #0191ff;
	}

	.records {
		margin: 20rpx 0 0 310rpx;
		color: #0191ff;
	}

	.btn {
		margin-bottom: 100rpx;
	}
</style>